package com.jinx.demo_log.service.impl;

import com.jinx.demo_log.domain.SysOperLog;
import com.jinx.demo_log.service.MongoDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class MongoDBServiceImpl implements MongoDBService {
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public Integer createCollection(String collectionName) {
        // 先判断集合是否存在
        if(mongoTemplate.collectionExists(collectionName)){
            return -2;
        }else{
            // 创建一个集合
            mongoTemplate.createCollection(collectionName);
            // 判断集合是否存在
            if(mongoTemplate.collectionExists(collectionName)){
                return 1;
            }else{
                return -1;
            }
        }
    }

    @Override
    public void add(Collection<?> batchToSave, String collectionName) {
        createCollection(collectionName);
        Collection<?> objects = mongoTemplate.insert(batchToSave, collectionName);
        System.out.println(objects);
    }

    @Override
    public void delete(Query query, Object obj, String collectionName) {
        mongoTemplate.remove(query, obj.getClass(), collectionName);
    }

    @Override
    public List<SysOperLog> findList(Query query, String collectionName) {
        return mongoTemplate.find(query, SysOperLog.class, collectionName);
    }

}
